package com.cmm.perfmonitor.trace;

import com.alibaba.fastjson.JSON;
import com.cmm.perfmonitor.trace.vo.HttpClientContent;
import com.cmm.perfmonitor.trace.vo.LogVo;
import com.cmm.perfmonitor.trace.vo.SqlContent;
import com.cmm.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @author caomm
 * @Title HttpClient 外部请求监控日志解析 合并
 * @Description TODO
 * @Date 2022/9/23 10:59
 */
public class HttpClientParse {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientParse.class);
    final static String fileName = "http.log";

    public static List<LogVo> parseHttpClient(List<LogVo> logLists) throws Exception {
        if (logLists.size() > 0) {
            // 获取sql日志信息
            File file = new File(FileUtils.getLocalPath() + "../log" + File.separator + fileName);
            List<HttpClientContent> httpLists = parse(file);
            if (httpLists.size() > 0) {
                for (LogVo logVo : logLists) {
                    long useTimeTotal = 0;
                    int timeCount = 0;
                    for (HttpClientContent httpClientContent : httpLists) {
                        if (logVo.getMethod().equals(httpClientContent.getClassMethod()) && logVo.getUuidKey().equals(httpClientContent.getUuidKey())) {
                            useTimeTotal += httpClientContent.getUseTime();
                            timeCount += 1;
                        }
                    }
                    logVo.setHttpUseTimeTotal(useTimeTotal);
                    logVo.setHttpTimeTotal(timeCount);
                }
            }
        }
        return logLists;
    }

    public static List<HttpClientContent> parse(File file) throws Exception {
        List<HttpClientContent> resultList = new ArrayList<>();

        FileInputStream fin = null;
        InputStreamReader reader = null;
        BufferedReader buffReader = null;
        StringBuilder logData = new StringBuilder();
        try {
            fin = new FileInputStream(file);
            reader = new InputStreamReader(fin);
            buffReader = new BufferedReader(reader);
            String strTmp = "";
            while ((strTmp = buffReader.readLine()) != null) {
                logData.append(strTmp);
            }
        } catch (Exception e) {
        } finally {
            if (fin != null) {
                buffReader.close();
                reader.close();
                fin.close();
            }
        }
        if (logData.length() > 0) {
            resultList = JSON.parseArray(logData.toString(), HttpClientContent.class);
        }
        return resultList;
    }
}
